/**
 * All-right reserved by gglu\lqz\qq 2010-2020
 */
package com.injury.hunan.spring.mvc.interceptor;

import java.text.MessageFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 请写上此类的主要功能
 * 
 * @author gglu
 * @version 2008年7月21日 上午1:09:30
 * @surpportjdk 1.5+
 * 
 */
public class PerformanceInterceptor implements HandlerInterceptor {

	private Logger logger = LoggerFactory.getLogger(getClass());

	private static final String TIME_COST = "TIME_COST";

	/**
	 * @author ThinKPad
	 * @since 2008年7月21日 上午1:09:30
	 * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		final Long begin = (Long) request.getAttribute(TIME_COST);
		if (null == begin) {
			request.setAttribute(TIME_COST, System.currentTimeMillis());
		}
		return true;
	}

	/**
	 * @author ThinKPad
	 * @since 2008年7月21日 上午1:09:30
	 * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
	 *      org.springframework.web.servlet.ModelAndView)
	 */
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	/**
	 * @author ThinKPad
	 * @since 2008年7月21日 上午1:09:30
	 * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
	 *      java.lang.Exception)
	 */
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

		final Long begin = (Long) request.getAttribute(TIME_COST);
		if (null == begin) {
			if (logger.isDebugEnabled()) {
				logger.debug("预处理请求时，未设置TIME_COST！！！");
			}
		} else {
			final Long end = System.currentTimeMillis();
			if (logger.isInfoEnabled()) {
				logger.info(MessageFormat.format("本次请求处理总耗时间--{0}--毫秒", (end - begin)));
			}
		}

	}

}
